package com.open.cloud.rbac.handler;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.inspur.micro.core.utils.AESUtil;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.ReadListener;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;

@Slf4j
public class SecureHttpRequestWrapper extends HttpServletRequestWrapper {
    //继承HttpServletRequestWrapper，创建装饰类，以达到修改HttpServletRequest参数的目的

    private byte[] decryptParam = null;

    public SecureHttpRequestWrapper(HttpServletRequest request) {
        super(request);
        if (request.getMethod().equals("POST")) {
            JSONObject paramObject = getJsonRequest(request);
            String secretStr = paramObject.getString("value");
            String decryptStr = AESUtil.decrypt(secretStr);
            this.decryptParam = decryptStr.getBytes(StandardCharsets.UTF_8);
        }
    }

    /**
     * 获取Post请求参数
     *
     * @param request
     * @return
     */
    private JSONObject getJsonRequest(HttpServletRequest request) {
        JSONObject result = null;
        StringBuilder sb = new StringBuilder();
        try (BufferedReader reader = request.getReader();) {
            char[] buff = new char[1024];
            int len;
            while ((len = reader.read(buff)) != -1) {
                sb.append(buff, 0, len);
            }
            result = JSON.parseObject(sb.toString());
        } catch (IOException e) {
            log.error("", e);
        }
        return result;
    }

    @Override
    public ServletInputStream getInputStream() throws IOException {
        return new ServletInputStream() {
            @Override
            public boolean isFinished() {
                return false;
            }

            @Override
            public boolean isReady() {
                return false;
            }

            @Override
            public void setReadListener(ReadListener readListener) {

            }

            final ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(decryptParam);

            @Override
            public int read() throws IOException {
                return byteArrayInputStream.read();
            }
        };
    }

    @Override
    public BufferedReader getReader() throws IOException {
        return new BufferedReader(new InputStreamReader(getInputStream()));
    }
}
